package com.codeduck.config;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.descriptor.web.ContextResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jndi.JndiObjectFactoryBean;

import javax.naming.NamingException;
import javax.sql.DataSource;

@Configuration
public class TomcatConfig {
    @Value("${spring.datasource.jndi-name}")
    private String jndiName;
    /**
     * 开启Tomcat的JNDI方式
     */
    @Bean
    @Profile("dev")
    public TomcatServletWebServerFactory tomcatContainer() {
        String url = "jdbc:mysql://localhost:3306/sabs_app_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
        String username = "sabs_master_user";
        String pwd = "sabs_master_pwd";
        String driver = "com.mysql.cj.jdbc.Driver";
        String jndiName = "mysqlDataSource";
        return new TomcatServletWebServerFactory() {
            @Override
            protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
                tomcat.enableNaming();
                return super.getTomcatWebServer(tomcat);
            }

            @Override
            protected void postProcessContext(Context context) {
                context.getNamingResources().addResource(getContextResource(jndiName, url, username, pwd, driver));
            }

            private ContextResource getContextResource(String jndiName, String url, String username, String pwd, String driver) {
                ContextResource context = new ContextResource();
                context.setName(jndiName);
                context.setType(DataSource.class.getName());
                context.setProperty("driverClassName", driver);
                context.setProperty("username", username);
                context.setProperty("password", pwd);
                context.setProperty("url", url);
                return context;
            }
        };
    }

//    @Bean("mysqlDataSource")
//    @Profile("dev")
//    public DataSource mysqlDataSource() throws NamingException {
//        JndiObjectFactoryBean factoryBean = new JndiObjectFactoryBean();
//        factoryBean.setJndiName(jndiName);
//        factoryBean.setProxyInterface(DataSource.class);
//        factoryBean.setLookupOnStartup(false);
//        factoryBean.afterPropertiesSet();
//        return (DataSource) factoryBean.getObject();
//    }
}
